// pages/orders/orders.js
import { URL, SER_KEY } from "../../config.js"
import { POST, GET } from "../../utils/request.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabData: [{
      id: 0,
      name: "待付款",
      imgUrl: '../../images/unpay.png'
    }, {
      id: 1,
      name: "待接单",
        imgUrl: '../../images/unshippe_gray.png'
    },{
      id: 2,
      name: "待发货",
        imgUrl: '../../images/unshippe_gray.png'
    }, {
      id: 3,
      name: "待收货",
        imgUrl: '../../images/unreceived_gray.png'
    }, {
      id: 4,
      name: "已完成",
        imgUrl: '../../images/Completed_gray.png'

      }, {
        id: 5,
        name: "退款/售后",
        imgUrl: '../../images/return_gray.png'
      }],
    tabId: 0,
    shopMsg:{},//店铺信息
    allList:[],
    status:'',
    noMore:false,
    contBox: false,
    show: false,
    contactCode:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },
  // tab点击
  chooseTab: function (e) {
    let id = Number(e.currentTarget.id)
    let index = e.currentTarget.dataset.index
    let data = this.data.tabData
    var status;
    switch(id){
      case 0:
      status='WAIT_BUYER_PAY'
      break;
      case 1:
      status='WAIT_SELLER_RECEIVE'
      break;
      case 2:
      status='WAIT_SELLER_SEND_GOODS'
      break;
      case 3:
      status='WAIT_BUYER_CONFIRM_GOODS'
      break;
      case 4:
      status='TRADE_SUCCESS'
      break;
      default:
      status='TRADE_REFUND_CLOSED'
    }
    // console.log(status)
    this.setData({ tabId: id,status:status},()=>this.getList());
  },
  //支付订单
  payOrder(e){
    // console.log(e.currentTarget.dataset.id)
    let that = this;
    let oderId = e.currentTarget.dataset.id
    let price = e.currentTarget.dataset.price
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY24;
    let data = {
      appid: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      shopId: that.data.shopMsg.id,
      orderId: oderId
    };
    GET(url, data, (ret) => {
      if (ret.statusCode == 200) {
        console.log(ret.data.pay)
        let data = ret.data.pay
        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: 'MD5',
          paySign: data.paySign,
          success (res) { 
            console.log(res)
            wx.navigateTo({
              url: '/pages/pay-successed/pay-successed?id='+oderId+'&price='+price,
            })
          },
          fail (res) { }
        })
      } else {
        wx.showToast({
          title: '数据走丢啦，请稍后再试',
          icon: 'none'
        });
      }
    })
  },
  deleteOrder(e){
    let that = this;
    let oderId = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    let list =that.data.allList
    wx.showModal({
      content: '确定要删除该订单？',
      showCancel: true,//是否显示取消按钮
      cancelText: "否",//默认是“取消”
      confirmText: "是",//默认是“确定”
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY26;
          let data = {
            appid: getApp().globalData.appId,
            sessionId: wx.getStorageSync('session_id'),
            orderId: oderId
          };
          GET(url, data, (ret) => {
            console.log(ret)
            if (ret.statusCode == 200) {
              console.log(ret)
              wx.showToast({
                title: '删除成功',
                icon:'none'
              })
              console.log(index)
              list.splice(index, 1)
              console.log(list)
              that.setData({
                allList: list
              })
              
            } else {
              wx.showToast({
                title: '数据走丢啦，请稍后再试',
                icon: 'none'
              });
            }
          })
        }
      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
    })
    
  },
  //联系商家
  contact() {
    console.log(this.data.contactCode)
    this.data.contactCode ? this.setData({
      contBox: true,
      show: true
    }) : ''
  },
  close(){
    this.setData({
      contBox: false,
      show: false
    })
  },
  getContactCode(){
    let that = this;
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY28;
    let data = {
      appid: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      shopId: that.data.shopMsg.id,
    };
    GET(url, data, (ret) => {
      if (ret.data.res == "SUCCESS") {
        console.log(ret)
        that.setData({
          contactCode:ret.data.url,
        })
      } else {
        wx.showToast({
          title: '数据走丢啦，请稍后再试',
          icon: 'none'
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let shopMsg = JSON.parse(wx.getStorageSync('shopData'))
    console.log(shopMsg)
    this.setData({
      shopMsg: shopMsg
    })
    let id = Number(getApp().globalData.tabId)
    console.log(id)
    this.data.contactCode? '':this.getContactCode()
    if(id!=undefined){
      var status
      switch (id) {
        case 0:
          status = 'WAIT_BUYER_PAY'
          break;
          case 1:
          status = 'WAIT_SELLER_RECEIVE'
          break;
        case 2:
          status = 'WAIT_SELLER_SEND_GOODS'
          break;
        case 3:
          status = 'WAIT_BUYER_CONFIRM_GOODS'
          break;
        case 4:
          status = 'TRADE_SUCCESS'
          break;
        default:
          status = 'TRADE_REFUND_CLOSED'
      }
      console.log(id, status)
      this.setData({ tabId: id, status: status }, () => this.getList()) 
    }
    
    // shopMsg ?this.setData({status:'WAIT_BUYER_PAY'},()=>this.getList()) :''
  },
  getList(){
    let that = this;
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY19;
    let data = {
      appid: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      shopId: that.data.shopMsg.id,
      status: that.data.status
    };
    GET(url, data, (ret) => {
      console.log(ret)
      if (ret.data.res == 'SUCCESS') {
        wx.stopPullDownRefresh()
        console.log(ret.data.lorder)
        this.setData({
          allList: ret.data.lorder
        })
      } else {
        wx.showToast({
          title: ret.data.errMsg+'请重新登陆',
          icon: 'none'
        });
      }
    })
  },
  beSure(e){
    let id=e.currentTarget.dataset.id
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确认收货后将不能修改',
      showCancel: true,//是否显示取消按钮
      cancelText: "取消",//默认是“取消”
      cancelColor: 'gray',//取消文字的颜色
      confirmText: "确认",//默认是“确定”
      confirmColor: 'skyblue',//确定文字的颜色
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
        } else {
          let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY30;
          let data = {
            appid: getApp().globalData.appId,
            sessionId: wx.getStorageSync('session_id'),
            orderId:id
          };
          GET(url, data, (ret) => {
            console.log(ret)
            if (ret.data.res == 'SUCCESS') {
              wx.showToast({
                title: '确认收货成功！',
                icon:'none'
              })
              this.getList()
            }else{
              wx.showToast({
                title: ret.data.errMsg,
                icon:'none'
              })
            }
          })
              }
      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
    })
    
  },
  refundOrder(e){
    let id=e.currentTarget.dataset.id
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要申请退款？',
      showCancel: true,//是否显示取消按钮
      cancelText:"否",//默认是“取消”
      cancelColor:'gray',//取消文字的颜色
      confirmText:"是",//默认是“确定”
      confirmColor: 'skyblue',//确定文字的颜色
      success: function (res) {
         if (res.cancel) {
            //点击取消,默认隐藏弹框
         } else {
            //点击确定
            let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY29;
    let data = {
      appid: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      orderId: id
    };
    GET(url, data, (ret) => {
      console.log(ret)
      if (ret.data.res == 'SUCCESS') {
        wx.showToast({
          title: ret.data.errMsg,
          icon:'none'
        })
        setTimeout(function(){
          that.getList()
        },1500)
      } else {
        wx.showToast({
          title: ret.data.errMsg,
          icon: 'none'
        });
      }
    })
         }
      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
   })
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    getApp().globalData.tabId=0

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    getApp().globalData.tabId=0
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function (e) {
    // console.log(e)
    let list = this.data.allList
    let lastIndex = list.length - 1
    let lastTime = list[lastIndex].timestamp
    // console.log(lastTime)
    let that = this;
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY25;
    let data = {
      appid: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      shopId: that.data.shopMsg.id,
      timestamp: lastTime,
      staus:that.data.status
    };
    GET(url, data, (ret) => {
      if (ret.statusCode == 200) {
        if (ret.data.lorder.length>0){
          list = list.concat(ret.data.lorder)
          that.setData({
            allList:list
          })
        }else{
          that.setData({
            noMore:true
          })
        }
      } else {
        wx.showToast({
          title: '数据走丢啦，请稍后再试',
          icon: 'none'
        });
      }
    })
  },
  //加载更多
  getMoreList(){

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})